<!--
 * @Author: 袁三金
 * @Date: 2023-10-13 10:47:45
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-10-22 14:47:13
 * @Description: 请填写简介
-->
<template>
  <div>
    <!-- 三级分类组件 -->
    <Category :scene="scene"></Category>
    <div v-show="scene == 0">
      <el-card style="margin: 10px 0;">
        <el-button type="primary" icon="Plus" size="default" :disabled="categoryStore.C3ID ? false : true"
          @click="attrChange">添加属性</el-button>
        <el-table style="width:100%; margin:10px 0;" border :data="categoryStore.AttrList">
          <el-table-column prop="date" label="序号" type="index" width="80px" align="center" />
          <el-table-column prop="attrName" label="属性名称" width="120px" />
          <el-table-column prop="attrValueList" label="属性值名称">
            <template #="{ row }">
              <el-tag style="margin:5px;" v-for="item in row.attrValueList" :key="item.id">{{ item.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #="{ row }">
              <el-button icon="Edit" type="warning" size="small" @click="updateAttr(row)"></el-button>
              <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" title="你确定要删除吗？"
                @confirm="confirmEvent(row.id)" width="200px">
                <template #reference>
                  <el-button icon="Delete" type="danger" size="small"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div v-show="scene == 1">
      <el-card style="margin: 10px 0;">
        <el-form ref="formRef" :model="attrParams" label-width="auto" :inline="true">
          <el-form-item label="属性名称">
            <el-input v-model="attrParams.attrName" placeholder="请输入属性值" />
          </el-form-item>
        </el-form>
        <el-button icon="Plus" :disabled="attrParams.attrName ? false : true" @click="addAttr"
          type="primary">添加属性值</el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-table :data="attrParams.attrValueList" style="margin: 10px 0;" border>
          <el-table-column label="序号" width="180" type="index" align="center" />
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-input @blur="tosearch(row, $index)" :ref="(vc: any) => inputArr[$index] = vc" v-if="row.flag"
                placeholder="请输入属性值名称" v-model="row.valueName"></el-input>
              <div v-else @click="toedit(row, $index)"> {{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template #="{ $index }">
              <el-button icon="Delete" type="danger" size="small"
                @click="attrParams.attrValueList.splice($index, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="save" :disabled="attrParams.attrValueList.length > 0 ? false : true">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue';
import useCategoryStore from '@/store/modules/category';
import type { Attr, AttrValue } from '@/api/product/attr/type';
import { AddOrUpdateAttr, DeleteAttr } from '@/api/product/attr';
import { ElMessage } from 'element-plus';
// 收集新增的属性的数据
let attrParams = reactive<Attr>({
  attrName: '',
  categoryId: '',//三级分类的id
  categoryLevel: 3,//分类等级
  attrValueList: [
  ],
})
let categoryStore = useCategoryStore();
watch(() => categoryStore.C3ID, () => {
  if (!categoryStore.C3ID) return;
  categoryStore.getAttr();
})
let scene = ref<number>(0);
const attrChange = () => {
  attrParams.attrValueList = [];
  attrParams.attrName = '';
  scene.value = 1;
  // 收集新增的属性的三级分类id
  attrParams.categoryId = categoryStore.C3ID;
};
const cancel = () => {
  scene.value = 0;
}
// 准备一个数组，将来存储对应的组件实例
let inputArr = ref<any>([])
// 添加属性值对象
const addAttr = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true
  })
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  })
}
const save = async () => {
  let result = await AddOrUpdateAttr(attrParams);
  // console.log(result);
  if (result.code == 200) {
    scene.value = 0;
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功'
    });
    // 重新获取一下已有的数据
    categoryStore.getAttr();

  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败'
    })
  }
};
// 修改属性
const updateAttr = (row:Attr) => {
  scene.value = 1;
  // Object.assign方法进行对象合并，深拷贝JSON.parse(JSON.stringify(row))，row为被拷贝的对象
  Object.assign(attrParams,JSON.parse(JSON.stringify(row)))
}
// 删除属性
const confirmEvent = async (id: number) => {
  let result = await DeleteAttr(id);
  if (result.code == 200) {
    scene.value = 0;
    ElMessage({
      type: 'success',
      message: id + '删除成功'
    });
    // 重新获取一下已有的数据
    categoryStore.getAttr();
  } else {
    ElMessage({
      type: 'error',
      message: id + '删除失败'
    })
  }

}

// 变查看模式
const tosearch = (row: AttrValue, $index: number) => {
  // 非法情况判断1
  if (row.valueName.trim() == '') {
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: 'error',
      message: '属性是不能为空'
    })
    return;
  }
  // 非法情况2
  let repeat = attrParams.attrValueList.find((item) => {
    if (item != row) {
      return item.valueName === row.valueName;
    }
  })
  if (repeat) {
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: 'error',
      message: '属性值重复'
    })
    return;
  }

  row.flag = false
}
// 变编辑模式
const toedit = (row: AttrValue, $index: number) => {
  row.flag = true
  nextTick(() => {
    inputArr.value[$index].focus();
  })
}
onBeforeUnmount(()=>{
  categoryStore.$reset();
})
</script>

<style scoped></style>
